#include <QSettings>
#include "MainModule.h"
#include "Logger.h"


MainModule::MainModule(QWidget* parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
    QSettings ini(QCoreApplication::applicationDirPath() + "/settings.ini", QSettings::IniFormat);
    _worker.reset(new Worker(ini));
}

void MainModule::Execute()
{
	logger.addn("Execution started");

	CreateTrayIcon(); 
	ShowTrayIcon();
	StartWorker();
} 

void MainModule::CreateTrayIcon()
{
	CreateMenu();

	_trayIcon = QSystemTrayIconPtr(new QSystemTrayIcon(QIcon(":/tray"), this));
	_trayIcon->setContextMenu(_trayIconMenu.get());
}

void MainModule::CreateMenu()
{
	CreateMenuActions();

	_trayIconMenu = QMenuPtr(new QMenu());

    _trayIconMenu->addAction(_labelAction.get());
	_trayIconMenu->addSeparator();
	_trayIconMenu->addAction(_quitAction.get());
}

void MainModule::CreateMenuActions()
{
    _labelAction = QActionPtr(new QAction("MDB Watcher", this));
    _quitAction  = QActionPtr(new QAction("&Exit", this));

    connect(_quitAction.get(), SIGNAL(triggered()), SLOT(Quit()));
}

void MainModule::StartWorker()
{
    _worker->start();
}

void MainModule::StopWorker()
{
	_worker->quit();
}

void MainModule::ShowTrayIcon()
{
	if (_trayIcon)
		_trayIcon->show();
}

void MainModule::HideTrayIcon()
{
	if (_trayIcon)
		_trayIcon->hide();
}

void MainModule::Quit()
{
    StopWorker();
    HideTrayIcon();
    logger.addn("== MDBSerial quit ==");
    qApp->quit();
}